package com.sann.spring.util;

import java.sql.SQLException;

/** 工具类：和事务管理相关的工具类，它包含了开启事务，提交事务，回滚事务和释放连接 */
public class TransactionManager {

    /** 用于获取跟当前线程相关的 Connection对象 */
    /**采用Setter注入*/
    private ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    /** 开启事务 */
    public void beginTransaction(){
        try {
            // 关闭自动提交事务，改用手动提交
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /** 提交事务 */
    public void commit(){
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /** 回滚事务 */
    public void rollback(){
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /** 释放连接,解绑Thread 上的Connection连接 */
    public void release(){
        try {
            connectionUtil.getThreadConnection().close();//还回连接池中
            connectionUtil.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
